using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace TST.SharePoint.Shared.WebControls
{
    /// <summary>
    /// Template object for a column. To be used in a Grid object. 
    /// Render a non-clickable checkbox, based on a boolean value in the datasource.
    /// </summary>
    public class HyperlinkColumn : ITemplate
    {
        private string _fieldName;
        private bool _useImage;

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="boolFieldName">The field name of the boolean field.</param>
        public HyperlinkColumn(string fieldName, bool renderAsImage)
        {
            _fieldName = fieldName;
            _useImage = renderAsImage;
        }

        public void InstantiateIn(Control container)
        {
            if (container != null)
            {
                HyperLink link = new HyperLink();
                link.ID = string.Concat("HyperlinkField_", _fieldName);
                link.DataBinding +=new EventHandler(link_DataBinding);
                container.Controls.Add(link);
            }
        }

        void link_DataBinding(object sender, EventArgs e)
        {
            HyperLink link = (HyperLink)sender;
            if (!string.IsNullOrEmpty(_fieldName))
            {
                GridViewRow container = (GridViewRow)link.NamingContainer;
                string value = ((System.Data.DataRowView)container.DataItem)[_fieldName].ToString();
                if (value.IndexOf(",") > 0 && (!value.EndsWith(",")))
                {
                    if (_useImage)
                        link.ImageUrl = value.Substring(0, value.IndexOf(","));
                    else
                        link.NavigateUrl = value.Substring(0, value.IndexOf(","));
                    link.Text = value.Substring(value.IndexOf(",") + 1);
                }
                else
                {
                    if (_useImage)
                        link.ImageUrl = value;
                    else
                        link.NavigateUrl = value;
                    link.Text = value;
                }
            }
        }

    }
}
